package com.atguigu.ssyx.rabbitmq.service;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 监听商品上下架服务发送的消息
 */
@Service
public class RabbitMQService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param exchange: 交换机
     * @param routingKey: 路由键
     * @param message: 消息
     * @return boolean
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
        return true;
    }

    /**
     * 发送延迟消息
     * @param exchange: 交换机
     * @param routingKey: 路由键
     * @param message: 消息
     * @param delayTime: 延迟时间
     * @return boolean
     */
    public boolean sendDelayMessage(String exchange, String routingKey, Object message, int delayTime) {
        // 发送消息时，设置延迟时间
        rabbitTemplate.convertAndSend(exchange, routingKey, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 设置延迟时间
                message.getMessageProperties().setDelay(delayTime * 1000);
                return message;
            }
        });
        return true;
    }
}
